import "@babylonjs/core/Debug/debugLayer";
import "@babylonjs/inspector";
import "@babylonjs/loaders/glTF";
import { Engine, Scene, ArcRotateCamera, Vector3, HemisphericLight, Mesh, MeshBuilder } from "@babylonjs/core";

class App {
    canvas: HTMLCanvasElement;
    engine: Engine;
    scene: Scene;

    /**
     * 构建方法
     */
    constructor() {
        // create the canvas html element and attach it to the webpage
        this.canvas = document.createElement("canvas");
        this.canvas.style.width = "100%";
        this.canvas.style.height = "100%";
        this.canvas.id = "gameCanvas";
        document.body.appendChild(this.canvas);

        // initialize babylon scene and engine
        this.engine = new Engine(this.canvas, true);
        this.scene = new Scene(this.engine);

        this.init_scene();
    }

    /**
     * 初始化场景相关内容
     */
    init_scene():void {
        let camera: ArcRotateCamera = new ArcRotateCamera("Camera", Math.PI / 2, Math.PI / 2, 2, Vector3.Zero(), this.scene);
        camera.attachControl(this.canvas, true);
        let light1: HemisphericLight = new HemisphericLight("light1", new Vector3(1, 1, 0), this.scene);
        let sphere: Mesh = MeshBuilder.CreateSphere("sphere", { diameter: 1 }, this.scene);

        // hide/show the Inspector
        window.addEventListener("keydown", (ev) => {
            this.on_keydown(ev);
        });

    }

    /**
     * 主运行方法
     */
    run():void {
        // run the main render loop
        this.engine.runRenderLoop(() => {
            this.scene.render();
        });

    }

    /**
     * 键盘按下事件处理
     * @param ev 键盘按下事件
     */
    on_keydown(ev: KeyboardEvent):void {
        // Shift+Ctrl+Alt+I
        if (ev.shiftKey && ev.ctrlKey && ev.altKey && ev.code === "KeyI") { // 73 -- i
            if (this.scene.debugLayer.isVisible()) {
                this.scene.debugLayer.hide();
            } else {
                this.scene.debugLayer.show();
            }
        }        
    }

}
let app = new App();
app.run();
